﻿//'
//' DotNetNuke® - http://www.dotnetnuke.com
//' Copyright (c) 2002-2010
//' by DotNetNuke Corporation
//'
//' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
//' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
//' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
//' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//'
//' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
//' of the Software.
//'
//' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
//' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
//' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
//' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
//' DEALINGS IN THE SOFTWARE.
//'

var MSG_TYPE_UNDEFINED = '0';
var MSG_TYPE_ENTER = '1';
var MSG_TYPE_LEAVE = '2';
var MSG_TYPE_CHAT = '3';
var MSG_TYPE_POLL = '4';

var XML_EMPTYMESSAGE = '<DnnChatMessage ID="{ID}" DT="{DT}" CONTENTCDATA="{CT}" MT="{MT}" />';

var last_previous;
var last_current;
var count_of_msgs_displayed = 0;

function getMessageXML(text, type) {
    //We're done pretty quick when it's just a polling message
    if (type === MSG_TYPE_POLL) {
        return "";
    }
    
    var xmlDoc = new dnn.xml.createDocument(); 
    // var _inputField = document.getElementById(inputField);

    // Load the result-xml document
    xmlDoc.loadXml(XML_EMPTYMESSAGE);

    // Get the message element
    var elmMsg = xmlDoc.rootNode(); //at this point we're sure there's only one
    //set the attributes
    text = replacePlus(text); 
    elmMsg.setAttribute("CONTENTCDATA", text);
    //elmMsg.setAttribute("SN", msg.sender);
    elmMsg.setAttribute("MT", type);

    return xmlDoc.getXml();
    //return retval;
}
function replacePlus(s) { //ToDO: is used before it was defined, must be changed
    var tempS;
    tempS = s.replace(/\+/gi, '&#43;');
    return tempS;
}

function getChatMessageXML(inputField) {
    var retval = getMessageXML(inputField.value, MSG_TYPE_CHAT);

    //clean the input box
    inputField.value = "";

    return retval;

}

function exitChat() {
    oTxt.value = "[exited]"; //TODO: [LOCALIZE] Localize text
    DoChatCallBack(oTxt);
}

function receiveChatMessage(result, context) {
    try {
        
        //alert("result before: " + result);  // for testing only
        while ((result.length > 0) && !(result.charAt(0) == '<')) {
            result = result.slice(1);
        }



        //alert("result after: " + result);  //for test only

        var dom = new dnn.xml.createDocument(); 
        
        // Load the result-xml document
        dom.loadXml(result);

        // Get the top node
        var topNode = dom.childNodes(0).childNodes(1);
       // alert("topNode " + topNode);  //for testing only

        var moduleID = topNode.getAttribute('MID');

        //Context is filled with "Chatwindow"
        var objDiv = context;

        var messageNode;

        //when ModuleID is null, there's not much we can do
        if (moduleID == null) {
            //alert("module id is null");  //for testing only
            return;
        }
        else {

            last_current = topNode.childNodes(topNode.childNodeCount() - 1).getAttribute('ID');
            if (last_current == last_previous) {
               // alert("last_current is last_prev"); /for testing only
                return;
            }

            last_previous = last_current;

        }


        var text = "";
        var content = "";
        var sender = "";
        var type = MSG_TYPE_UNDEFINED;

        // Loop through the child elements
        for (var i = 0; i <= topNode.childNodeCount() - 1; i++) {
            messageNode = topNode.childNodes(i);
            // Get the element that the Node is about
            content = messageNode.getAttribute('CONTENTCDATA');
            sender = messageNode.getAttribute('SN');
            type = messageNode.getAttribute('MT');

            if (type == MSG_TYPE_CHAT) {
                var _senderSays;
                _senderSays = eval('senderText_' + moduleID);
                _senderSays = _senderSays.replace('{0}', sender);

                text += "<span class='" + eval('cssClassSender_' + moduleID) + "'>" + _senderSays + "</span><br>";
                text += "<span class='" + eval('cssClassMessage_' + moduleID) + "'>" + content + "</span><br>";
            }
            else {
                text += "<span class='" + eval('cssClassSender_' + moduleID) + "'><I>" + content + "</I></span><br>";
            }

            eval('max_msgs_displayed_' + moduleID + ' += 0;');
            if (eval('max_msgs_displayed_' + moduleID + ' > DisplayCapacity_' + moduleID)) {
                objDiv.removeChild(objDiv.firstChild);
            }
        }

        var newDiv = document.createElement("div");
        newDiv.innerHTML = text;
        objDiv.appendChild(newDiv);
        objDiv.scrollTop = objDiv.scrollHeight;

    }
    catch (exc) {
        var errDiv = document.createElement("div");
        errDiv.innerHTML = "<span class='NormalRed'>Client-error: " + exc.message + "</span><br>";
        context.appendChild(errDiv);
    }
}

function receiveChatMessageError(result, context) {
    var newDiv = document.createElement("div");
    newDiv.innerHTML = "<span class='NormalRed'>Server-error: " + result + "</span><br>";
    context.appendChild(newDiv);
}
function receiveChatMessageErrorNoShow(result, context) {
    // don't show the error in this case
}
